﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Xml.Serialization;
using System.Xml.Linq;
using System.Text;
using System.Windows.Forms;
using SGP;

namespace Animation_Manager
{
    public partial class Form1 : Form
    {
       public enum resizeDirection { None, LEFT, RIGHT, UP, DOWN, LEFT_UP, LEFT_DOWN, RIGHT_UP, RIGHT_DOWN };

        bool isRunning;
        //DateTime currentTime;
        int currentTime;
        float elapsedTime;
        List<Animation> myAnimations;
        List<Frame> frames;
        Animation myAnimation;
        ManagedDirect3D mD3D;
        ManagedTextureManager mTM;
        bool isMouseDown;
        bool isMouseDrag;
        Point origin;
        Point corner;
        Rectangle rect;
        int framelistSize;
        Frame tempFrame;
        bool drawn;
        Color filter;
        int count;
        float mouseHoldTime;
        bool isDragging;
        OpenFileDialog oDlg;
        FolderBrowserDialog fDlg;
        SaveFileDialog sDlg;
        string rPath;
        string filename;
        string fullPath;
        int imgID;
        ColorDialog cDlg;
        bool playing;
        float timeWaited;
        Rectangle animFrame;
        int increment;
        int now;
        int currentFrame;
        int spriteX;
        int spriteY;

        public float ElapsedTime
        {
            get { return elapsedTime; }
            set { elapsedTime = value; }
        }

        public bool IsRunning
        {
            get { return isRunning; }
            set { isRunning = value; }
        }

        public Form1()
        {
            InitializeComponent();
            currentTime = 0;
            IsRunning = true;
            myAnimation = new Animation();
            myAnimations = new List<Animation>();
            frames = new List<Frame>();
            triggerTypes.Items.Add(TriggerTypes.None);
            triggerTypes.Items.Add(TriggerTypes.Particle);
            triggerTypes.Items.Add(TriggerTypes.Attack);
            triggerTypes.Items.Add(TriggerTypes.Sound);
            myAnimation.ImageID = -1;
            myAnimation.FilterColor = System.Drawing.Color.Empty;
            isMouseDown = false;
            isMouseDrag = false;
            drawn = false;
            framelistSize = 0;
            imgID = -1;
            timeWaited = 0.0f;
            increment = 1;
            currentFrame = 0;

            spriteX = 0;
            spriteY = 0;

        }

        public bool LoadFolder()
        {
            fDlg = new FolderBrowserDialog();

            if (DialogResult.OK == fDlg.ShowDialog())
            {
                rPath = fDlg.SelectedPath;
            }

            else if (DialogResult.Cancel == fDlg.ShowDialog())
            {
                return false;
            }
            return true;
        }

        public void InitializeD3D()
        {
            mD3D = ManagedDirect3D.Instance;
            mTM = ManagedTextureManager.Instance;
            mD3D.InitManagedDirect3D(sheetDisplay);
            mD3D.InitManagedDirect3D(animationDisplay);
            mTM.InitManagedTextureManager(mD3D.Device, mD3D.Sprite);
           // mSC = new ManagedSwapChain(mD3D, mD3D.Device.);
           // mD3D
        }

        private void addFrame_Click(object sender, EventArgs e)
        {
            Create_Frame();  
        }

        private void Create_Frame()
        {
            Frame tempFrame = new Frame();
            Point anchor = new Point((int)anchorX.Value, (int)anchorY.Value);
            float dur = new float();
            framelistSize++;
            
            //TriggerTypes trig = new int();

            dur = (float)durationUpDown.Value;
            //trig = (TriggerTypes)triggerTypes.Items[triggerTypes.SelectedIndex];


            tempFrame.AnchorPoint = anchor;
            tempFrame.Duration = dur;
            //if (RectWidth.Value < 0)
            //{
            //    tempFrame.FrameLocation = new Point((int)
            //}

            if (drawn == true)
            {
                tempFrame.FrameLocation = new Point(rect.X, rect.Y);
                tempFrame.FrameSize = new Size(rect.Width, rect.Height);
            }

            else
            {
                tempFrame.FrameLocation = new Point((int)RectX.Value, (int)RectY.Value);
                tempFrame.FrameSize = new Size((int)RectWidth.Value, (int)RectHeight.Value);
            }
           
            if (frameName.Text == " ")
                frameName.Text = "Generic";

            tempFrame.Name = frameName.Text;


            if (triggerTypes.SelectedIndex < 0)
            {
                //MessageBox.Show("Please choose a trigger type!");
                triggerTypes.SelectedIndex = 0;
            }

            tempFrame.Trigger = (TriggerTypes)triggerTypes.Items[triggerTypes.SelectedIndex];

            tempFrame.TriggerName = triggerName.Text;

            frameList.Items.Add(tempFrame);
            frames.Add(tempFrame);
            myAnimation.Frame = new Frame();
            myAnimation.Frame = tempFrame;
            myAnimation.Frames.Add(myAnimation.Frame);
            drawn = false;
        }

        //private void RectX_ValueChanged(object sender, EventArgs e)
        //{

        //    myAnimation.Frame.X = (int)RectX.Value;
                
        //}

        public void Updater()
        {
            //elapsedTime += (float)((System.DateTime.Now - currentTime).Milliseconds) / 1000.0f;
           // currentTime = Environment.TickCount;
            now = Environment.TickCount;
            elapsedTime = (float)(now - currentTime) / 1000.0f;
            currentTime = now;

            if (elapsedTime > 0.125f)
                elapsedTime = 0.125f;

            if (imgID == -1)
            {
                fCommandBox.Enabled = false;
                animCommand.Enabled = false;
                frameCommandbox.Enabled = false;
            }

            else
            {
                fCommandBox.Enabled = true;
            }

            if (animationList.Items.Count > 0)
            {
                frameCommandbox.Enabled = true;
            }

            if (frameList.Items.Count > 0)
            {
                fCommandBox.Enabled = true;
            }

            if (myAnimation.FilterColor != System.Drawing.Color.Empty)
            {
                animCommand.Enabled = true;
            }

            if (myAnimation.ImageID != -1)
            {
                Size textureSize = new Size(mTM.GetTextureWidth(myAnimation.ImageID), mTM.GetTextureHeight(myAnimation.ImageID));
                //sheetDisplay.AutoScrollMinSize = textureSize;
                //spriteX = sheetDisplay.AutoScrollPosition.X;
                //spriteY = sheetDisplay.AutoScrollPosition.Y;
            }

            int frameListSize = frameList.Items.Count;
            
            if (playing)
            {
                timeWaited += elapsedTime;
                
                if (timeWaited >= myAnimations[animationList.SelectedIndex].Frames[frameList.SelectedIndex].Duration )
                {
                    timeWaited -= myAnimations[animationList.SelectedIndex].Frames[frameList.SelectedIndex].Duration;

                    //if(myAnimations[animationList.SelectedIndex].Looping == true)
                    //    if(frameList.SelectedIndex ==
                    if (myAnimations[animationList.SelectedIndex].Oscillating == false)
                    {
                        if (frameList.SelectedIndex < frameList.Items.Count - 1)
                        {
                            frameList.SelectedIndex = frameList.SelectedIndex + increment;
                            currentFrame = frameList.SelectedIndex;
                        }

                        else
                            currentFrame++;
                    }

                    else
                    {
                        frameList.SelectedIndex = frameList.SelectedIndex + increment;
                    }

                    if (myAnimations[animationList.SelectedIndex].Oscillating == true)
                    {
                        if (increment > 0)
                        {
                            if (frameList.SelectedIndex >= frameListSize - 1)
                            {
                                increment = -increment;
                            }
                        }

                        else
                        {
                            if (frameList.SelectedIndex < 1)
                            {
                                frameList.SelectedIndex = 0;
                                increment = -increment;
                            }
                        }
                    }

                    else
                    {
                        if (currentFrame >= frameListSize )
                        {
                            if (myAnimations[animationList.SelectedIndex].Looping == true)
                            {
                                frameList.SelectedIndex = 0;
                                currentFrame = 0;
                            }

                            else
                            {
                                playing = false;
                                frameList.SelectedIndex = frameListSize - 1;
                            }
                        }
                    }
                }
            }


        }

        public void Render()
        {
            Render_sheet_Display();
            Render_animation_Display();
        }   

        private void Render_sheet_Display()
        {
            mD3D.ChangeDisplayParam(sheetDisplay);
            mD3D.Clear(0, 0, 0);
            mD3D.DeviceBegin();
            mD3D.SpriteBegin();
            

            if (animationList.SelectedIndex != -1)
            {
                myAnimation = myAnimations[animationList.SelectedIndex];
            }

            if (myAnimation.ImageID != -1)
                mTM.Draw(myAnimation.ImageID, spriteX, spriteY, 1.0f, 1.0f, Rectangle.Empty, 0, 0, 0.0f, 255, 255, 255, 255);
            mD3D.SpriteEnd();


            if (framelistSize >= 0)
            {
                if (animationList.SelectedIndex != -1)
                    frames = myAnimations[animationList.SelectedIndex].Frames;

                foreach (Frame f in frames)
                {
                    if (frameList.SelectedIndex > -1)
                    {
                        if (f == (Frame)frameList.Items[frameList.SelectedIndex])
                        {
                            //Rectangle tempRect;
                            
                                //tempRect = newRect;

                            
                            Rectangle tempRect = new Rectangle(f.FrameLocation.X + spriteX, f.FrameLocation.Y + spriteY, f.FrameSize.Width, f.FrameSize.Height);
                            mD3D.DrawEmptyRect(tempRect, 0, 0, 255, 1.5f);

                            if (f.AnchorPoint.X > 0 && f.AnchorPoint.Y > 0)
                            {
                                //mD3D.DrawLine(
                            }

                            mD3D.DrawLine(f.FrameLocation.X - f.AnchorPoint.X - 5 + spriteX, f.FrameLocation.Y + f.AnchorPoint.Y + spriteY, f.FrameLocation.X - f.AnchorPoint.X + 5 + spriteX, f.FrameLocation.Y + f.AnchorPoint.Y+ spriteY, 255, 255, 255);
                            mD3D.DrawLine(f.FrameLocation.X - f.AnchorPoint.X + spriteX, f.FrameLocation.Y + f.AnchorPoint.Y - 5 + spriteY, f.FrameLocation.X - f.AnchorPoint.X + spriteX, f.FrameLocation.Y + f.AnchorPoint.Y + spriteY, 255, 255, 255);
                            //Rectangle anchRect = new Rectangle(f.FrameLocation.X + f.FrameSize.Width + f.AnchorPoint.X, f.AnchorPoint.Y + f.FrameSize.Height + f.AnchorPoint.Y, 5, 5);
                            //mD3D.DrawRect(anchRect, 255, 255, 255);
                        }

                        else
                        {
                            Rectangle tempRect = new Rectangle(f.FrameLocation.X + spriteX, f.FrameLocation.Y + spriteY, f.FrameSize.Width, f.FrameSize.Height);
                            mD3D.DrawEmptyRect(tempRect, 255, 0, 0, 1.5f);
                        }
                    }

                    else
                    {
                        Rectangle tempRect = new Rectangle(f.FrameLocation.X + spriteX, f.FrameLocation.Y + spriteY, f.FrameSize.Width, f.FrameSize.Height);
                        mD3D.DrawEmptyRect(tempRect, 255, 0, 0, 1.5f);
                    }
                   
                }
               

                //if (drawn == true)
                //{
                if (rect != null)
                {
                    Rectangle tempR = new Rectangle(rect.X + spriteX, rect.Y + spriteY, rect.Width, rect.Height);
                    //rect.X = rect.X -
                    //rect.Y = rect.Y - spriteY;
                    mD3D.DrawEmptyRect(tempR, 125, 125, 0, 1.5f);
                }
                
               // }
            }

            if (isMouseDown == true)
            {
                mD3D.DrawText(rect.Left.ToString(), 0, 0, 255, 255, 255);
                mD3D.DrawText(",", 28, 0, 255, 255, 255);
                mD3D.DrawText(rect.Top.ToString(), 35, 0, 255, 255, 255);

                if (isMouseDrag == true)
                {
                    mD3D.DrawText(",", 63, 0, 255, 255, 255);
                    mD3D.DrawText(rect.Right.ToString(), 70, 0, 255, 255, 255);
                    mD3D.DrawText(",", 98, 0, 255, 255, 255);
                    mD3D.DrawText(rect.Bottom.ToString(), 105, 0, 255, 255, 255);
                }
            }

           
            mD3D.DeviceEnd();
            mD3D.Present(sheetDisplay);
        }

        private void Render_animation_Display()
        {
            mD3D.ChangeDisplayParam(animationDisplay);
            mD3D.Clear(0, 0, 0);
            mD3D.DeviceBegin();
            mD3D.SpriteBegin();

            if (animationList.SelectedIndex != -1)
            {
                if (frameList.SelectedIndex != -1)
                {
                    Point loc = new Point(myAnimations[animationList.SelectedIndex].Frames[frameList.SelectedIndex].FrameLocation.X, myAnimations[animationList.SelectedIndex].Frames[frameList.SelectedIndex].FrameLocation.Y);
                    Size size = new Size(myAnimations[animationList.SelectedIndex].Frames[frameList.SelectedIndex].FrameSize.Width, myAnimations[animationList.SelectedIndex].Frames[frameList.SelectedIndex].FrameSize.Height);

                    animFrame = new Rectangle(loc.X, loc.Y, size.Width, size.Height);

                    if (myAnimation.ImageID != -1)
                    {
                        int width = 50 + (myAnimations[animationList.SelectedIndex].Frames[frameList.SelectedIndex].FrameSize.Width);
                        int posX = width;
                        Point anchorPt = new Point(myAnimations[animationList.SelectedIndex].Frames[frameList.SelectedIndex].AnchorPoint.X, myAnimations[animationList.SelectedIndex].Frames[frameList.SelectedIndex].AnchorPoint.Y);
                        anchorPt.X = width - anchorPt.X;
                        mTM.Draw(myAnimation.ImageID, posX - anchorPt.X, 200 - (myAnimations[animationList.SelectedIndex].Frames[frameList.SelectedIndex].AnchorPoint.Y), 1.0f, 1.0f, animFrame, 0, 0, 0.0f, 255, 255, 255, 255);
                    }
                   //int width = r.right - r.left;
                   //nPosX += width * (int)fScaleX;
                   //anchor.x = width - anchor.x;
                }
            }

            
            foreach (Frame f in frames)
            {
                //Rectangle rect = new Rectangle(f.FrameLocation.X, f.FrameLocation.Y, f.FrameSize.Width, f.FrameSize.Height);
                //mD3D.DrawEmptyRect(rect, 255, 0, 0, 1.2f);
            }
            mD3D.SpriteEnd();
            mD3D.DeviceEnd();
            mD3D.Present(animationDisplay);
        }

        private void Form1_FormClosed(object sender, FormClosedEventArgs e)
        {
             IsRunning = false;
        }

        private void loadImageToolStripMenuItem_Click(object sender, EventArgs e)
        {
            oDlg = new OpenFileDialog();
            oDlg.Filter = "All Files(*.*)|*.*|Images(*.png, .bmp, .gif)|*.png|*.bmp|*.gif";
            oDlg.DefaultExt = "png";
            oDlg.InitialDirectory = rPath;
            if (DialogResult.OK == oDlg.ShowDialog())
            {
                //System.IO.StreamReader reader = new System.IO.StreamReader(dlg.FileName);
                
                filename = "\\" +  oDlg.SafeFileName.ToString();
                fullPath = rPath + "\\" + filename;

                if (myAnimation.ImageID != -1)
                {
                    mTM.ReleaseTexture(myAnimation.ImageID);
                    myAnimation.ImageID = -1;
                }

                myAnimation.ImageID = imgID = mTM.LoadTexture(fullPath, filter.ToArgb());
                myAnimation.FileName = oDlg.SafeFileName.ToString();
                ResizeScrollBars();
            }
            
        }

        private void RectX_ValueChanged(object sender, EventArgs e)
        {
           // int X = (int)RectX.Value;

            if (drawn == false)
            if (frameList.SelectedIndex >= 0 && frameList.SelectedIndex < frameList.Items.Count)
            {
                Frame f = (Frame)frameList.Items[frameList.SelectedIndex];
                Point loc = new Point((int)RectX.Value, f.FrameLocation.Y);
                // Size size = new Size((int)(f.FrameLocation.X + f.FrameSize.Width), (int)(f.FrameLocation.Y + f.FrameSize.Height));
                //Size size = new Size(
                //((Frame)frameList.Items[frameList.SelectedIndex])
                f.FrameLocation = loc;
                frameList.Items[frameList.SelectedIndex] = f;
                frames[frameList.SelectedIndex] = f;
            }

            else
            {
                //if (drawn == true)
              //  rect.X = X;
            }
       }

        private void RectY_ValueChanged(object sender, EventArgs e)
        {
            //int Y = (int)RectY.Value;

            if (drawn == false)
                if (frameList.SelectedIndex >= 0 && frameList.SelectedIndex < frameList.Items.Count)
            {
                Frame f = (Frame)frameList.Items[frameList.SelectedIndex];
                Point loc = new Point(f.FrameLocation.X, (int)RectY.Value);
                // Size size = new Size((int)(f.FrameLocation.X + f.FrameSize.Width), (int)(f.FrameLocation.Y + f.FrameSize.Height));
                //Size size = new Size(
                //((Frame)frameList.Items[frameList.SelectedIndex])
                f.FrameLocation = loc;
                frameList.Items[frameList.SelectedIndex] = f;
                frames[frameList.SelectedIndex] = f;
            }

            else
            {
               // if (drawn == true)
                 //   rect.Y = Y;
            }
        }

        private void RectWidth_ValueChanged(object sender, EventArgs e)
        {
            //int width = (int)(RectWidth.Value);

            if (drawn == false)
                if (frameList.SelectedIndex >= 0 && frameList.SelectedIndex < frameList.Items.Count)
            {
                Frame f = (Frame)frameList.Items[frameList.SelectedIndex];
                //Point loc = new Point(f.FrameLocation.X, (int)RectY.Value);
                Size size = new Size((int)(RectWidth.Value), (int)(f.FrameSize.Height));
                //Size size = new Size(
                //((Frame)frameList.Items[frameList.SelectedIndex])
                f.FrameSize = size;
                frameList.Items[frameList.SelectedIndex] = f;
                frames[frameList.SelectedIndex] = f;
            }

            else
            {
                //if (drawn == true)
                   // rect.Width = width;
            }
        }

        private void RectHeight_ValueChanged(object sender, EventArgs e)
        {
            //int height = (int)(RectHeight.Value);

            if(drawn == false)
                if (frameList.SelectedIndex >= 0 && frameList.SelectedIndex < frameList.Items.Count)
            {
                Frame f = (Frame)frameList.Items[frameList.SelectedIndex];
                //Point loc = new Point(f.FrameLocation.X, (int)RectY.Value);
                Size size = new Size((int)(f.FrameSize.Width), (int)(RectHeight.Value));
                //Size size = new Size(
                //((Frame)frameList.Items[frameList.SelectedIndex])
                f.FrameSize = size;
                frameList.Items[frameList.SelectedIndex] = f;
                frames[frameList.SelectedIndex] = f;
            }

            else
            {
               // if (drawn == true)
                    //rect.Height = height;
            }
        }

        private void sheetDisplay_MouseDown(object sender, MouseEventArgs e)
        {
            isMouseDown = true;
            Point offset = e.Location;
          
            offset.X -= sheetDisplay.AutoScrollPosition.X;
            offset.Y -= sheetDisplay.AutoScrollPosition.Y;

            int offsetX = e.X - spriteX;
            int offsetY = e.Y - spriteY;
           
            origin = new Point(e.X, e.Y);

            if (e.Button == MouseButtons.Left)
            {
                isDragging = true;
            }

            //mouseHoldTime += elapsedTime.Seconds;

            if (isMouseDrag == false)
            {
                if (rect != null)
                   rect = new Rectangle(0, 0, 0, 0);

               rect = new Rectangle(offsetX, offsetY, 0, 0);
            }
            
        }

        private void sheetDisplay_MouseMove(object sender, MouseEventArgs e)
        {
            Point offset = e.Location;

            offset.X -= sheetDisplay.AutoScrollPosition.X;
            offset.Y -= sheetDisplay.AutoScrollPosition.Y;

            int offsetX = e.X - spriteX;
            int offsetY = e.Y - spriteY;

            if (isMouseDown == true)
            {
               // mouseHoldTime += elapsedTime.Seconds;
                corner = new Point(offset.X, offset.Y);
                isMouseDrag = true;
                
                //corner = new Point(e.Location.X - sheetDisplay.AutoScrollPosition.X, e.Location.Y - sheetDisplay.AutoScrollPosition.Y);
                if (isMouseDrag)
                {
                   
                  frameList.SelectedIndex = -1;
                  int width = corner.X - origin.X;
                  int height = corner.Y - origin.Y;

                  rect = new Rectangle(rect.X, rect.Y, offsetX - rect.X, offsetY - rect.Y);
                    
                }
                
            }
        }

        private void sheetDisplay_MouseUp(object sender, MouseEventArgs e)
        {
            isMouseDown = false;
            isDragging = false;
          
            if (isMouseDrag)
            {
                if (frameList.SelectedIndex == -1)
                {
                    RectX.Value = (decimal)rect.Left;
                    RectY.Value = (decimal)rect.Top;
                    RectWidth.Value = (decimal)rect.Width;//(rect.Right - rect.Left);
                    RectHeight.Value = (decimal)rect.Height;
                }
                
                frameList.SelectedIndex = -1;

                isMouseDrag = false;
            }
 
        }

        private void frameList_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (frameList.SelectedIndex != -1 && frameList.SelectedIndex < frameList.Items.Count)
            {
                ((Frame)frameList.Items[frameList.SelectedIndex]).Selected = !((Frame)frameList.Items[frameList.SelectedIndex]).Selected;

                Frame newFrame = (Frame)frameList.Items[frameList.SelectedIndex];
                RectX.Value = (decimal)newFrame.FrameLocation.X;
                RectY.Value = (decimal)newFrame.FrameLocation.Y;
                RectWidth.Value = (decimal)newFrame.FrameSize.Width;
                RectHeight.Value = (decimal)newFrame.FrameSize.Height;
                triggerTypes.SelectedItem = newFrame.Trigger;
                triggerName.Text = newFrame.TriggerName;
                anchorX.Value = (decimal)newFrame.AnchorPoint.X;
                anchorY.Value = (decimal)newFrame.AnchorPoint.Y;
                durationUpDown.Value = (decimal)newFrame.Duration;
            }

        }

        private void filterColorToolStripMenuItem_Click(object sender, EventArgs e)
        {
            cDlg = new ColorDialog();
            // myAnimation.FilterColor = cDlg.Color;dlg.Color = panel1.BackColor;

            if (DialogResult.OK == cDlg.ShowDialog())
            {
                filter = cDlg.Color;
                myAnimation.FilterColor = filter;

                if (myAnimation.ImageID != -1)
                {
                    mTM.ReleaseTexture(myAnimation.ImageID);
                    myAnimation.ImageID = -1;
                }

                myAnimation.ImageID = imgID = mTM.LoadTexture(fullPath, filter.ToArgb());

                if (oDlg != null)
                {
                    myAnimation.FileName = oDlg.SafeFileName.ToString();
                    ResizeScrollBars();
                }
            }
            
        }

        private void sheetDisplay_Click(object sender, EventArgs e)
        {
            
            //drawn = false;
            
          
        }

        private void sheetDisplay_Click(object sender, MouseEventArgs e)
        {
            count = 0;
            Point offset = e.Location;

            offset.X -= sheetDisplay.AutoScrollPosition.X;
            offset.Y -= sheetDisplay.AutoScrollPosition.Y;
            int offsetX = e.X + spriteX;
            int offsetY = e.Y + spriteY;
            foreach (Frame f in frames)
            {
                //Point click_area = new Point(f.FrameLocation.X + 2, f.FrameLocation.X - 2);
                if (offsetX >= f.FrameLocation.X && offsetX <= f.FrameSize.Width + f.FrameLocation.X && offsetY >= f.FrameLocation.Y && offsetY <= f.FrameSize.Height + f.FrameLocation.Y)
                {
                    break; 
                    
                }

                else
                {
                    frameList.SelectedIndex = -1;
                }
                count++;
            }
            if(framelistSize > 0 && count < framelistSize)
            frameList.SelectedIndex = count;


        }

        private void addAnimation(object sender, EventArgs e)
        {
            myAnimation = new Animation();
            myAnimation.Oscillating = oscillateCheck.Checked;
            myAnimation.Looping = loopCheck.Checked;
            myAnimation.ImageID = imgID;
            myAnimation.Name = animationName.Text;
            myAnimation.FilterColor = cDlg.Color;
            myAnimation.Filepath = rPath;
            myAnimation.FileName = oDlg.SafeFileName;
            foreach (Frame f in frames)
            {
                myAnimation.Frame = new Frame();
                myAnimation.Frame = f;
                myAnimation.Frames.Add(myAnimation.Frame);
            }
            myAnimation.NumFrames = framelistSize;
            myAnimations.Add(myAnimation);
            animationList.Items.Add(myAnimation);
      
            frameList.Items.Clear();

            frames = new List<Frame>();
            framelistSize = 0;

            
        }

        private void newToolStripMenuItem_Click(object sender, EventArgs e)
        {
            
            //for (int i = 0; i < framelistSize; ++i)
            //{
            //    frameList.Items.Remove(frameList.Items[i]);
            //}
            frameList.Items.Clear();
            frameList = new ListBox();
            frames = new List<Frame>();
        }

        private void loadAnimationsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            oDlg = new OpenFileDialog();
            oDlg.Filter = "All Files|*.*|Xml Files|*.xml";
            oDlg.FilterIndex = 2;
            myAnimations = new List<Animation>();
            oDlg.InitialDirectory = rPath;
            
            frameList.Items.Clear();
            if (animationList.Items.Count > 0)
            {
                animationList.Items.Clear();
                //animationList = new ListBox();
            }

            if (DialogResult.OK == oDlg.ShowDialog())
            {
               
                XElement xRoot = XElement.Load(oDlg.FileName);
                IEnumerable<XElement> xAniTypes = xRoot.Elements();
                IEnumerable<XElement> xAnimations = xAniTypes.Elements();

                foreach (XElement xAniType in xAniTypes)
                {
                    myAnimation = new Animation();

                    XAttribute xFile = xAniType.Attribute("File");
                    XAttribute xNumFrame = xAniType.Attribute("NumFrames");
                    XAttribute xOscillate = xAniType.Attribute("Oscillating");
                    XAttribute xLoop = xAniType.Attribute("Looping");
                    XAttribute xRed = xAniType.Attribute("Red");
                    XAttribute xGreen = xAniType.Attribute("Green");
                    XAttribute xBlue = xAniType.Attribute("Blue");
                    XAttribute xAnimName = xAniType.Attribute("Name");

                    string file = Convert.ToString(xFile.Value);
                    string animName = Convert.ToString(xAnimName.Value);
                    int red = int.Parse(xRed.Value);
                    int green = int.Parse(xGreen.Value);
                    int blue = int.Parse(xBlue.Value);

                    int oscilCheck = int.Parse(xOscillate.Value);
                    int loopCheck = int.Parse(xLoop.Value);

                    if (oscilCheck == 1)
                    {
                        myAnimation.Oscillating = true;
                    }

                    else
                    {
                        myAnimation.Oscillating = false;
                    }

                    if (loopCheck == 1)
                    {
                        myAnimation.Looping = true;
                    }

                    else
                    {
                        myAnimation.Looping = false;
                    }
                    



                    myAnimation.FilterColor = Color.FromArgb(255, red, green, blue);
                    filter = myAnimation.FilterColor;
                    myAnimation.FileName = file;
                    myAnimation.Name = animName;

                    file = "\\" + file;
                    fullPath = rPath + "\\" + file;

                    myAnimation.ImageID = imgID = mTM.LoadTexture(fullPath, myAnimation.FilterColor.ToArgb());

                    foreach (XElement xAnimation in xAnimations)
                    {
                        Frame tempFrame = new Frame();

                        XAttribute xLeft = xAnimation.Attribute("left");
                        XAttribute xTop = xAnimation.Attribute("top");
                        XAttribute xRight = xAnimation.Attribute("right");
                        XAttribute xBottom = xAnimation.Attribute("bottom");
                        XAttribute xAnchX = xAnimation.Attribute("anchorX");
                        XAttribute xAnchY = xAnimation.Attribute("anchorY");
                        XAttribute xDur = xAnimation.Attribute("Duration");
                        XAttribute xTrigType = xAnimation.Attribute("TriggerType");
                        XAttribute xTrigger = xAnimation.Attribute("TriggerName");
                        XAttribute xName = xAnimation.Attribute("FrameName");

                        tempFrame.AnchorPoint = new Point(int.Parse(xAnchX.Value), int.Parse(xAnchY.Value));
                        tempFrame.Duration = float.Parse(xDur.Value);
                        tempFrame.FrameLocation = new Point(int.Parse(xLeft.Value), int.Parse(xTop.Value));
                        Size size = new Size(int.Parse(xRight.Value), int.Parse(xBottom.Value));

                        tempFrame.FrameSize = new Size((size.Width - tempFrame.FrameLocation.X), (size.Height - tempFrame.FrameLocation.Y));
                        tempFrame.Name = Convert.ToString(xName.Value);

                        int type = int.Parse(xTrigType.Value);
                        tempFrame.Trigger = (TriggerTypes)type;

                        tempFrame.TriggerName = Convert.ToString(xTrigger.Value);

                        frames.Add(tempFrame);
                        myAnimation.Frame = tempFrame;
                        myAnimation.Frames.Add(myAnimation.Frame);

                    }

                    animationList.Items.Add(myAnimation);
                    myAnimations.Add(myAnimation);
                   
                }
                
            }
            ResizeScrollBars();
        }

        private void saveAnimationsToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            sDlg = new SaveFileDialog();
            sDlg.Filter = "All Files|*.*|Xml Files|*.xml";
            sDlg.FilterIndex = 2;
            sDlg.DefaultExt = "xml";
            

            if (DialogResult.OK == sDlg.ShowDialog())
            {
                XElement xRoot = new XElement("Animations");

                foreach (Animation a in myAnimations)
                {
                    XElement aniType = new XElement("AnimationType");
                    xRoot.Add(aniType);
                    XAttribute path = new XAttribute("File", a.FileName);
                    aniType.Add(path);
                    XAttribute numFrames = new XAttribute("NumFrames", a.NumFrames);
                    aniType.Add(numFrames);
                    XAttribute aniName = new XAttribute("Name", a.Name);
                    aniType.Add(aniName);

                    XAttribute isOscillating;
                    XAttribute isLooping;

                    if(a.Oscillating == true)
                    isOscillating = new XAttribute("Oscillating", 1);

                    else
                        isOscillating = new XAttribute("Oscillating", 0);

                    aniType.Add(isOscillating);

                    if (a.Looping == true)
                        isLooping = new XAttribute("Looping", 1);

                    else
                        isLooping = new XAttribute("Looping", 0);

                    aniType.Add(isLooping);



                    XAttribute red = new XAttribute("Red", a.FilterColor.R);
                    aniType.Add(red);

                    XAttribute blue = new XAttribute("Green", a.FilterColor.G);
                    aniType.Add(blue);

                    XAttribute green = new XAttribute("Blue", a.FilterColor.B);
                    aniType.Add(green);

                    XAttribute name = new XAttribute("Name", a.Name);

                    foreach (Frame f in a.Frames)
                    {
                        XElement animation = new XElement("Animation");
                        aniType.Add(animation);

                        XAttribute left = new XAttribute("left", f.FrameLocation.X);
                        animation.Add(left);

                        XAttribute top = new XAttribute("top", f.FrameLocation.Y);
                        animation.Add(top);

                        XAttribute right = new XAttribute("right", (f.FrameLocation.X + f.FrameSize.Width));
                        animation.Add(right);

                        XAttribute bottom = new XAttribute("bottom", (f.FrameLocation.Y + f.FrameSize.Height));
                        animation.Add(bottom);

                        XAttribute anchX = new XAttribute("anchorX", f.AnchorPoint.X);
                        animation.Add(anchX);

                        XAttribute anchY = new XAttribute("anchorY", f.AnchorPoint.Y);
                        animation.Add(anchY);

                        XAttribute dur = new XAttribute("Duration", f.Duration);
                        animation.Add(dur);

                        int type = (int)f.Trigger;

                        XAttribute trig = new XAttribute("TriggerType", type);
                        animation.Add(trig);

                        XAttribute trigName = new XAttribute("TriggerName", f.TriggerName);
                        animation.Add(trigName);

                        XAttribute frameName = new XAttribute("FrameName", f.Name);
                        animation.Add(frameName);

                    }
                }

                xRoot.Save(sDlg.FileName);
            }
        }

        private void anchorX_ValueChanged(object sender, EventArgs e)
        {
            if (frameList.SelectedIndex != -1 && frameList.SelectedIndex < frameList.Items.Count)
            {
                Frame tempFrame = (Frame)frameList.Items[frameList.SelectedIndex];
                Point tempAnchor = new Point((int)anchorX.Value, tempFrame.AnchorPoint.Y);
                tempFrame.AnchorPoint = tempAnchor;
                frameList.Items[frameList.SelectedIndex] = tempFrame;
                if (frames.Count > 0)
                frames[frameList.SelectedIndex] = tempFrame;
            }
        }

        private void anchorY_ValueChanged(object sender, EventArgs e)
        {
            if (frameList.SelectedIndex != -1 && frameList.SelectedIndex < frameList.Items.Count)
            {
                Frame tempFrame = (Frame)frameList.Items[frameList.SelectedIndex];
                Point tempAnchor = new Point(tempFrame.AnchorPoint.X, (int)anchorY.Value);
                tempFrame.AnchorPoint = tempAnchor;
                frameList.Items[frameList.SelectedIndex] = tempFrame;
                if(frames.Count > 0)
                frames[frameList.SelectedIndex] = tempFrame;
            }
        }

        private void removeFrame_Click(object sender, EventArgs e)
        {
            if (frameList.SelectedIndex != -1 && frameList.SelectedIndex < frameList.Items.Count)
            {
                frames.Remove(frames[frameList.SelectedIndex]);
                frameList.Items.Remove(frameList.Items[frameList.SelectedIndex]);
                frameList.SelectedIndex = -1;
                
            }
        }

        private void oscillateCheck_CheckedChanged(object sender, EventArgs e)
        {
            if (animationList.SelectedIndex != -1)
            {
                if (oscillateCheck.Checked == true)
                    myAnimations[animationList.SelectedIndex].Oscillating = true;

                else
                    myAnimations[animationList.SelectedIndex].Oscillating = false;
            }
        }

        private void loopCheck_CheckedChanged(object sender, EventArgs e)
        {
            if (animationList.SelectedIndex != -1)
            {
                if (loopCheck.Checked == true)
                    myAnimations[animationList.SelectedIndex].Looping = true;

                else
                    myAnimations[animationList.SelectedIndex].Looping = false;
            }
        }

        private void animationList_SelectedIndexChanged(object sender, EventArgs e)
        {
            frameList.Items.Clear();
            playing = false;
            if (animationList.SelectedIndex != -1)
            {
                loopCheck.Checked = myAnimations[animationList.SelectedIndex].Looping;
                oscillateCheck.Checked = myAnimations[animationList.SelectedIndex].Oscillating;
            

                foreach (Frame f in myAnimations[animationList.SelectedIndex].Frames)
                {
                    frameList.Items.Add(f);
                }
                frameList.SelectedIndex = 0;
            }
        }

        private void animRemove_Click(object sender, EventArgs e)
        {
            if (animationList.SelectedIndex != -1)
            {
                myAnimations.Remove(myAnimations[animationList.SelectedIndex]);
                animationList.Items.Remove(animationList.Items[animationList.SelectedIndex]);
                
            }
        }

        private void playButton_Click(object sender, EventArgs e)
        {

            if (animationList.SelectedIndex != 1)
            {
                playing = true;
                frameList.SelectedIndex = 0;
            }

        }

        private void durationUpDown_ValueChanged(object sender, EventArgs e)
        {
            if (frameList.SelectedIndex != -1)
            {
                Frame tempFrame = (Frame)frameList.Items[frameList.SelectedIndex];
                tempFrame.Duration = (float)durationUpDown.Value;
                frameList.Items[frameList.SelectedIndex] = tempFrame;
                myAnimation.Frame = tempFrame;
                myAnimation.Frames[frameList.SelectedIndex] = tempFrame;
            }
        }

        private void stopButton_Click(object sender, EventArgs e)
        {
            playing = false;
        }

        private void Reset_Frame_Click(object sender, EventArgs e)
        {
            frameList.SelectedIndex = 0;
        }

        private void Next_Frame_Click(object sender, EventArgs e)
        {

            if (frameList.SelectedIndex != -1 && frameList.SelectedIndex < frameList.Items.Count)
            {
                int frameListSize = frameList.Items.Count;

               frameList.SelectedIndex += increment;

               if (myAnimations[animationList.SelectedIndex].Oscillating == true)
               {
                   if (increment > 0)
                   {
                       if (frameList.SelectedIndex >= frameListSize - 1)
                       {
                           increment = -increment;
                       }
                   }

                   else
                   {
                       if (frameList.SelectedIndex < 1)
                       {
                           frameList.SelectedIndex = 0;
                           increment = -increment;
                       }
                   }
               }

               else
               {
                   if (frameList.SelectedIndex >= frameListSize)
                   {
                       if (myAnimations[animationList.SelectedIndex].Looping == true)
                       {
                           frameList.SelectedIndex = 0;
                       }
                   }
               }
            }
        }

        private void vScrollBar1_Scroll(object sender, ScrollEventArgs e)
        {
            //if (e.NewValue > e.OldValue)
            //{
            //    spriteY--; //(e.NewValue - e.OldValue);
            //}
            //
            //if (e.NewValue < e.OldValue)
            //{
            //    spriteY++; //(e.NewValue - e.OldValue);
            //}

            spriteY -=  e.NewValue - e.OldValue;

            //if(rect != null)
               
            //RectY.Value += (decimal(e.OldValue - e.NewValue);
        }

        private void hScrollBar1_Scroll(object sender, ScrollEventArgs e)
        {
            if (myAnimation.ImageID != -1)
            {
                spriteX -= (e.NewValue - e.OldValue);
            }

            //if(rect != null)
               // rect.X = rect.X - spriteX;
           
        }

        private void Form1_Resize(object sender, EventArgs e)
        {
            ResizeScrollBars();
        }

        private void ResizeScrollBars()
        {
            if (myAnimation.ImageID == -1)
                return;

            if (sheetDisplay.Width < mTM.GetTextureWidth(myAnimation.ImageID) + vScrollBar1.Width)
            {
                hScrollBar1.Maximum = mTM.GetTextureWidth(myAnimation.ImageID) + 10 + vScrollBar1.Width - sheetDisplay.Width;
                RectX.Maximum = (decimal)(mTM.GetTextureWidth(myAnimation.ImageID) + 10 + vScrollBar1.Width);
                hScrollBar1.Enabled = true;

            }
            else
            {
                spriteX = 0;
                hScrollBar1.Enabled = false;
            }

            if (sheetDisplay.Height < mTM.GetTextureHeight(myAnimation.ImageID) + hScrollBar1.Size.Height)
            {
                vScrollBar1.Maximum = mTM.GetTextureHeight(myAnimation.ImageID) + 10 + hScrollBar1.Size.Height - sheetDisplay.Height;
                RectY.Maximum = (decimal)(mTM.GetTextureHeight(myAnimation.ImageID) + 10 + hScrollBar1.Height);
                vScrollBar1.Enabled = true;
            }
            else
            {
                spriteY = 0;
                vScrollBar1.Enabled = false;
            }
        }

    }
}
